export function generateHeatData(points, x, y, w, h, gradient, grain, opacity) {
    const heatData = [];
    const sampleSize = grain; // Sample size of each grid cell

    for (let i = x + Math.floor(sampleSize / 2); i < x + w; i += sampleSize) {
        for (let j = y + Math.floor(sampleSize / 2); j < y + h; j += sampleSize) {
            const interpolatedTemp = calculateInterpolatedTemp(i, j, points, gradient);
            heatData.push({
                x: i,
                y: j,
                intensity: interpolatedTemp,
                opacity: (1 - opacity) * interpolatedTemp + opacity
            });
        }
    }

    return heatData;
}

export function parsePercentPoints(percentPoints, width, height, minTemp, maxTemp) {
    const points = percentPoints.map(point => ({
        x: point.x * width,
        y: point.y * height,
        temp: normalize(point.temp, minTemp, maxTemp),
        intensity: 'intensity' in point ? point.intensity : 1
    }));
    return points;
}

function normalize(temp, minTemp, maxTemp) {
    if (minTemp == maxTemp) {
        return 0;
    }
    let fixMinTemp = minTemp > maxTemp ? maxTemp : minTemp;
    let t = Math.min(maxTemp, Math.max(fixMinTemp, temp));
    let nt = (t - fixMinTemp) / (maxTemp - fixMinTemp);
    return nt;
}

function calculateInterpolatedTemp(cx, cy, points, gradient) {
    var totalTemp = 0;
    points.forEach(point => {
        const { x, y, temp, intensity } = point;
        const distance = Math.sqrt(Math.pow(x - cx, 2) + Math.pow(y - cy, 2));
        //const cTemp = intensity * temp / (distance * gradient + 1);    // 反比例曲线
        const cTemp = intensity * temp * Math.exp(-distance * gradient); // 指数曲线
        totalTemp += cTemp;
        totalTemp = Math.min(1, totalTemp);
    });
    return totalTemp;
}